package Arrays.DinamicArray;

import java.lang.reflect.Array;
import java.util.Arrays;

public class DinamicArray {

    private static final int DynamicArrayCap = 5;
    private Object[] item;
    private int cap;
    private int length;


    // 无参构造
    DinamicArray() {
        this.item = new Object[DynamicArrayCap];
        this.cap = DynamicArrayCap;
        this.length = 0;

    }

    // 有参构造--> 指定了数组长度
    public DinamicArray(int item) {
        this.item = new Object[item];
        this.cap = item;
        this.length = 0;
    }

    // 获取数组长度
    public int getCap() {
        return cap;
    }

    // 获取数组元素
    public int getLength() {
        return length;
    }

    // 队尾插入
    public void push(Object data) {
        this.length++;
        this.expandCap();
        this.item[this.getLength() - 1] = data;
    }

    // 队尾删除
    public Object pop() {
        Object e;
        if (this.getLength() < 0) {
            System.out.println("err this array is null");
            return null;
        }
        e = this.item[this.getLength() - 1];
        this.item[this.getLength() - 1] = null;
        this.length--;

        this.reduceCap();
        return e;
    }

    // 动态扩容 超过数组容量，按照当前容量的 2 倍扩容
    public void expandCap() {
        int size;
        Object[] newItem = new Object[0];
        // 如果数组元素大于等于容量
        if (this.getLength() <= this.cap) {
            return;
        }
        size = getCap() * 2;
        newItem = new Object[size];
        for (int i = 0; i < this.getLength() - 1; i++) {
            newItem[i] = this.item[i];
        }
        this.item = newItem;
        this.cap = size;
    }

    // 动态缩容 数组元素个数为当前容量 1/4 时，缩容为当前容量的一半
    public void reduceCap() {
        int size;
        Object[] newItem = new Object[0];
        // 如果数组元素小于等于容量的4/1
        if (this.getLength() > this.cap / 4) {
            return;
        }
        size = this.getLength() / 2;
        newItem = new Object[size];
        for (int i = 0; i < getLength() - 1; i++) {
            newItem[i] = this.item[i];
        }
        this.item = newItem;
        this.cap = size;
    }

    // 获取元素
    public Object GetItem(int index) {
        if (index < 0 || index > this.getLength() - 1) {
            System.out.println("error list out of range");
            return null;
        }
        return this.item[index];
    }

    @Override
    public String toString() {
        return "Dynamic{" +
                "item=" + Arrays.toString(item) +
                '}';
    }
}


